/**
 * @Auther: ChenforCode
 * @Date: 2018/9/9 14:21
 * @Description: 完成学生界面的相关控制
 */
package cn.chenforcode.controller;

import cn.chenforcode.entity.Book;
import cn.chenforcode.entity.Student;
import cn.chenforcode.service.BookService;
import cn.chenforcode.service.BorrowService;
import cn.chenforcode.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private BorrowService borrowService;

    @Autowired
    private BookService bookService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private HttpSession session;

    @RequestMapping("/stu_main")
    public String stu_main(Model model) {
        //拿到当前用户名
        String name = (String) session.getAttribute("uname");

        //拿到当前学生对象
        Student student = studentService.getStudent(name);

        //拿到所有书籍
        List<Book> books = bookService.getAllBooks();

        //拿到未归还的书籍
        List<Book> books1 = borrowService.getNoReturn(name);
        model.addAttribute("stu_stu", student);
        model.addAttribute("stu_books", books);
        if (books1 != null) {
            model.addAttribute("stu_books_noret", books1);
        }
        return "stu_main";
    }

    @RequestMapping("/add")
    public String addBalance(String add) {
        long add_long = Long.parseLong(add);
        //拿到当前用户名
        String name = (String) session.getAttribute("uname");
        studentService.addBalance(name, add_long);
        return "redirect:stu_main";
    }

    @RequestMapping("/bor")
    public String borrow(String id) {
        //拿到当前用户名
        String name = (String) session.getAttribute("uname");

        String msg = borrowService.borrowBook(name, id);
        if ("success".equals(msg)) {
            if (session.getAttribute("bor_msg") != null) {
                session.removeAttribute("bor_msg");
            }
            return "redirect:stu_main";
        } else {
            session.setAttribute("bor_msg", "借书失败");
            return "redirect:stu_main";
        }
    }

    @RequestMapping("/ret")
    public String ret(String id) {
        //拿到当前用户名
        String name = (String) session.getAttribute("uname");
        if (session.getAttribute("bor_msg") != null) {
            session.removeAttribute("bor_msg");
        }
        borrowService.returnBook(name, id);
        return "redirect:stu_main";
    }
}
